package com.pozu.new_retail.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pozu.new_retail.dao.mapper.CommentMapper;
import com.pozu.new_retail.dao.mapper.UpvoteMapper;
import com.pozu.new_retail.dao.model.Comment;
import com.pozu.new_retail.dao.model.Upvote;
import com.pozu.new_retail.dao.vo.CommentMeVo;
import com.pozu.new_retail.dao.vo.CommentVo;
import com.pozu.new_retail.service.CommentService;

@Service("commentService")
public class CommentServiceImpl implements CommentService {

	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private UpvoteMapper upvoteMapper;
	
	@Override
	public List<CommentMeVo> queryCommentMeByMap(HashMap<String, Object> map) {
		return commentMapper.queryCommentMeByMap(map);
	}

	@Override
	public int queryCountByMap(HashMap<String, Object> map) {
		return commentMapper.queryCountByMap(map);
	}

	@Override
	public List<CommentVo> queryByMap(HashMap<String, Object> map) {
		
		long userId = Long.parseLong(map.get("userId").toString());
		
		List<CommentVo> vos = new ArrayList<CommentVo>();
		
		List<CommentVo> list = commentMapper.queryByMap(map);
		
		if (null != list && list.size() > 0) {
			for(CommentVo vo:list) {
				
				HashMap<String, Object> hashMap = new HashMap<String,Object>();

				hashMap.put("otherId", vo.getCommentId());
				hashMap.put("appId", map.get("appId"));
				hashMap.put("type", 1);
	
				/** 点赞数量 **/
				Integer upvoteNumber = upvoteMapper.queryCountByMap(hashMap);
				
				hashMap.put("userId", userId);
				/** 是否点赞 **/
				
				Upvote upvote = upvoteMapper.queryByMap(hashMap);
				
				if (null == upvote || upvote.getState() == 1) {
					vo.setUpvoteFlag(false);	
				}else {
					vo.setUpvoteFlag(true);
				}
				
				vo.setUpvoteNumber(upvoteNumber);
				
				
				vos.add(vo);
			}
		}
		
		return vos;
	}

	@Override
	public Comment queryByCommentId(long commentId) {
		return commentMapper.queryByCommentId(commentId);
	}

	@Override
	public Comment saveComment(Comment comment) {
		
		long time = System.currentTimeMillis();
		
		comment.setCreatedTime(time);
		comment.setUpdatedTime(time);
		commentMapper.insertComment(comment);
		
		return comment;
	}

	@Override
	public int updateComment(Comment comment) {
		
		comment.setUpdatedTime(System.currentTimeMillis());
		
		return commentMapper.updateComment(comment);
	}

	@Override
	public int batchInsert(List<Comment> comments) {
		return commentMapper.batchInsert(comments);
	}

	@Override
	public int queryMyCountByUserId(HashMap<String, Object> map) {
		return commentMapper.queryMyCountByUserId(map);
	}

}
